﻿#region Opis pliku
//-----------------------------------------------------------------------------
// GamePlayGUI.cs
// Autor: Jan Czarnowski
// 6.11.2012
//-----------------------------------------------------------------------------
#endregion

#region Using...

using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Content;
using System;
using System.Text;
using System.Collections.Generic;

#endregion

namespace pogra
{
    /// <summary>
    /// Klasa ekranu interfejsu użytkownika podczas gry. Podczas rozgrywki zajmuje się wyświetlaniem
    /// wszystkiego oprócz jednostek i mapy.
    /// </summary>
    class GamePlayGUI : GameScreen
    {
        #region pola

        // prostokąty reprezentujące górne i dolne gui
        Rectangle topBar = new Rectangle();
        Rectangle bottomBar = new Rectangle();

        // prostokąty reprezentujące obszary dolnego gui
        Rectangle miniMap;
        Rectangle selectionArea;
        Rectangle infoArea;
        Rectangle buildArea;

        // podreczne menu
        GameMenu popupMenu;

        // referencja do obiektu gameplayscreen, na ktorym wyswietlane jest to gui
        GamePlayScreen gamePlayScreen;

        // zmienne dotyczace przycisku "menu" w gornym gui
        Color buttonColor = Color.Gray;
        Rectangle buttonRect;

        // listy przycisków z poszczególnych obszarów GUI
        List<Button> buildButtonList = new List<Button>();
        List<Button> selectionButtonList = new List<Button>();
        List<Button> controlBuildingButtonList = new List<Button>();
        List<Button> controlUnitButtonList = new List<Button>();

        // liczba roznych typów jednostek - gdzies z gory trzba wziac jako stałą
        int typesCount = 3;
        
        // tabela tekstur ikon jednostek (przy wyborze w selectionArea)
        Texture2D[] typeTexTab;

        // zmienne pomocnicze przy stawianiu budynków
        bool buildingStarted = false;
        bool mouseFirstPressed;
        int buildingType = 0;
        Point mousePos;
        float buildingRot = 0;
        Point buildingOrigin;

        #endregion

        #region inicjalizacja

        /// <summary>
        /// Tworzy nowy obiekt GamePlayGUI.
        /// </summary>
        /// <param name="gamePlayScreen">GamePlayScreen, z którym związane jest to GUI</param>
        public GamePlayGUI(GamePlayScreen gamePlayScreen)
        {
            this.gamePlayScreen = gamePlayScreen;
        }

        public override void LoadContent()
        {
            // wymiary top i bottom paskow
            Rectangle viewRect = ScreenManager.ViewRect;
            bottomBar.X = 0;
            bottomBar.Y = (int) (0.8 * viewRect.Height);
            bottomBar.Width = viewRect.Width;
            bottomBar.Height = (int) (0.2 * viewRect.Height);

            topBar.Width = (int)(0.5 * viewRect.Width);
            topBar.Height = (int)(0.05 * viewRect.Height);
            topBar.X = (viewRect.Width - topBar.Width)/2;
            topBar.Y = 0;

            // obszary dolnego paska
            miniMap = new Rectangle(bottomBar.X + 5, bottomBar.Y + 5, bottomBar.Height + 40, bottomBar.Height - 10);
            selectionArea = new Rectangle(miniMap.Right + 10, miniMap.Y, 4*50 + 5*5, miniMap.Height);
            infoArea = new Rectangle(selectionArea.Right + 10, miniMap.Y, 800 - 20 - selectionArea.Width, miniMap.Height);
            buildArea = new Rectangle(infoArea.Right + 10, miniMap.Y, bottomBar.Width - infoArea.Right - 20, miniMap.Height);
            
            // dodajemy menu gry
            popupMenu = new GameMenu();
            ScreenManager.AddScreen(popupMenu);
            popupMenu.IsActive = false;

            // wczytywanie tekstur ikon
            typeTexTab = new Texture2D[typesCount];

            ContentManager content = ScreenManager.Game.Content;
            typeTexTab[0] = content.Load<Texture2D>("gruntIcon");
            typeTexTab[1] = content.Load<Texture2D>("tankIcon");
            typeTexTab[2] = content.Load<Texture2D>("heliIcon");

            // wczytywanie tekstur guzików
            Texture2D aggro = content.Load<Texture2D>("aggro");
            Texture2D passiv = content.Load<Texture2D>("passiv");
            Texture2D szyklinia = content.Load<Texture2D>("szyklinia");
            Texture2D szyktrojkat = content.Load<Texture2D>("szyktrojkat");
            Texture2D szyklosowy = content.Load<Texture2D>("szykrandom");
            Texture2D factoryTex = content.Load<Texture2D>("factoryicon");
            Texture2D barracksTex = content.Load<Texture2D>("homeicon");

            // inicjalizacja guzików

            // przyciski zaznaczania
            for (int i = 0; i < 3; ++i)
            {
                Button but = new Button(Vector2.Zero, typeTexTab[i], i);
                but.IsActive = false;
                but.IsHidden = true;
                selectionButtonList.Add(but);
            }

            #region przyciski kontroli jednostek

            Vector2 pos;

            // przycisk defensywnego nastawienia ID=0
            pos.X = infoArea.Right - 20 - 2 * passiv.Width;
            pos.Y = infoArea.Top + 10;
            Button buton = new Button(pos, passiv, 0);

            controlUnitButtonList.Add(buton);
            buton.IsActive = false;
            buton.IsHidden = true;

            // przycisk agresywnego nastawienia ID=1
            pos.X = infoArea.Right - 10 - passiv.Width;
            pos.Y = infoArea.Top + 10;
            buton = new Button(pos, aggro, 1);

            controlUnitButtonList.Add(buton);
            buton.IsActive = false;
            buton.IsHidden = true;

            // przycisk formacji luznej ID=2
            pos.X = infoArea.Right - 30 - 3*passiv.Width;
            pos.Y = infoArea.Top + passiv.Height + 20;
            buton = new Button(pos, szyklosowy, 2);

            controlUnitButtonList.Add(buton);
            buton.IsActive = false;
            buton.IsHidden = true;

            // przycisk formacji linii ID=3
            pos.X = infoArea.Right - 20 - 2 * passiv.Width;
            pos.Y = infoArea.Top + passiv.Height + 20;
            buton = new Button(pos, szyklinia, 3);

            controlUnitButtonList.Add(buton);
            buton.IsActive = false;
            buton.IsHidden = true;

            // przycisk formacji trojkata ID=4
            pos.X = infoArea.Right - 10 - passiv.Width;
            pos.Y = infoArea.Top + passiv.Height + 20;
            buton = new Button(pos, szyktrojkat, 4);

            controlUnitButtonList.Add(buton);
            buton.IsActive = false;
            buton.IsHidden = true;
            #endregion

            #region przyciski kontroli budynków
            // todo
            #endregion

            #region przyciski budowy

            // przycisk budowy fabryki
            pos.X = buildArea.Left + 10;
            pos.Y = buildArea.Top + 10;
            buton = new Button(pos, factoryTex, 0);

            buildButtonList.Add(buton);

            // przycisk budowy koszarów
            pos.X = buildArea.Left + 20 + factoryTex.Width;
            pos.Y = buildArea.Top + 10;
            buton = new Button(pos, barracksTex, 1);

            buildButtonList.Add(buton);
            #endregion
        }

        #endregion

        #region metody draw i update

        public override void Draw(GameTime gameTime)
        {
            RTSGame game = (RTSGame)ScreenManager.Game;
            ExtendedSpriteBatch exSpriteBatch = ScreenManager.ExtendedSpriteBatch;

            /* POCZATEK RYSOWANIA */
            exSpriteBatch.End();
            exSpriteBatch.Begin();
            
            // rysowanie górnej częsci gui
            drawTopBar(exSpriteBatch);            

            // rysowanie dolnej części gui
            drawBottomBar(exSpriteBatch);

            // przyciski----------------------------------------
            foreach (Button but in selectionButtonList)
                but.draw(exSpriteBatch);

            foreach (Button but in buildButtonList)
                but.draw(exSpriteBatch);

            foreach (Button but in controlUnitButtonList)
                but.draw(exSpriteBatch);

            foreach (Button but in controlBuildingButtonList)
                but.draw(exSpriteBatch);
            //--------------------------------------------------

            if (buildingStarted)
            {
                Texture2D buildTex = gamePlayScreen.EntityManager.getBuildingTex(buildingType);
                Rectangle sourceRect = new Rectangle(0, 0, buildTex.Width / 2, buildTex.Height);
                float scale = ((RTSGame)(ScreenManager.Game)).Camera.Zoom;
                Point pos;

                if(mouseFirstPressed)
                    pos = buildingOrigin;
                else
                    pos = mousePos;

                int sizeX = (int)(scale * buildTex.Width / 2);
                int sizeY = (int)(scale * buildTex.Height);
                exSpriteBatch.Draw(buildTex, new Rectangle(pos.X, pos.Y, sizeX, sizeY), sourceRect, Color.White, buildingRot, new Vector2(sizeX/2, sizeY/2), SpriteEffects.None, 1);
            }

            /* KONIE RYSOWANIA */
            exSpriteBatch.End();
            exSpriteBatch.Begin(SpriteSortMode.Deferred,
                                 BlendState.AlphaBlend,
                                 null,
                                 null,
                                 null,
                                 null,
                                game.Camera.GetTransformation(game.GraphicsDevice));
        }

        public override void Update(GameTime gameTime)
        {
            // sprawdzanie czy koniec gry
            if (gamePlayScreen.EntityManager.Kasa < 0 && gamePlayScreen.EntityManager.UnitAList.Count == 0)
                ScreenManager.AddScreen(new TextScreen("przegrana!", Color.Red));

            if (gamePlayScreen.EntityManager.UnitBList.Count == 0)
                ScreenManager.AddScreen(new TextScreen("wygrana!", Color.Green));


            // przyciski----------------------------------------
            foreach (Button but in selectionButtonList)
                but.update(gameTime.ElapsedGameTime);

            foreach (Button but in buildButtonList)
                but.update(gameTime.ElapsedGameTime);

            foreach (Button but in controlUnitButtonList)
                but.update(gameTime.ElapsedGameTime);

            foreach (Button but in controlBuildingButtonList)
                but.update(gameTime.ElapsedGameTime);
            //--------------------------------------------------

            handleBuildButtons();
            handleSelectionButtons();
            handleControlButtons();

        }

        #endregion

        #region metody publiczne

        public override void HandleInput(InputState input, bool otherScreenHasFocus, ref bool eventHandled)
        {
            Camera cam = ((RTSGame) ScreenManager.Game).Camera;
            GraphicsDevice dev = ScreenManager.Game.GraphicsDevice;
            mousePos.X = input.CurrentMouseState.X;
            mousePos.Y = input.CurrentMouseState.Y;
            
            // obsluga eventHandled-----------------------------------
            if (eventHandled || otherScreenHasFocus)
                return;

            if (input.IsNewMLeftButtonPressed())
                if (topBar.Contains(mousePos) || bottomBar.Contains(mousePos))
                    eventHandled = true;
            if (topBar.Contains(mousePos) || bottomBar.Contains(mousePos))
                eventHandled = true;
            //-------------------------------------------------------


            // obsluga przycisku ----------------------
            if (input.IsNewKeyPress(Keys.Escape) || (buttonRect.Contains(mousePos) && input.IsNewMLeftButtonPressed()))
                popupMenu.IsActive = true;

            if (buttonRect.Contains(mousePos))
                buttonColor = Color.Red;
            else
                buttonColor = Color.Gray;
            //---------------------------------------
       

            // obsluga ruchu kamery i zooma----------------------
            if (input.isNewMWheelUp())
                cam.Zoom += 0.1f * cam.Zoom;

            if (input.isNewMWheelDown())
                cam.Zoom -= 0.1f * cam.Zoom;

            if (input.CurrentKeyboardState.IsKeyDown(Keys.Right) ||  (input.CurrentMouseState.X >= ScreenManager.ViewRect.Width - 10 && input.CurrentMouseState.X <= ScreenManager.ViewRect.Width))
                cam.Pos += new Vector2(20 * 1 / cam.Zoom, 0);

            if (input.CurrentKeyboardState.IsKeyDown(Keys.Left) || (input.CurrentMouseState.X <= 10 && input.CurrentMouseState.X >= 0))
                cam.Pos += new Vector2(-20 * 1/cam.Zoom, 0);

            if (input.CurrentKeyboardState.IsKeyDown(Keys.Up) || (input.CurrentMouseState.Y <= 5 && input.CurrentMouseState.Y >= 0))
                cam.Pos += new Vector2(0, -20 * 1 / cam.Zoom);

            if (input.CurrentKeyboardState.IsKeyDown(Keys.Down) || (input.CurrentMouseState.Y >= ScreenManager.ViewRect.Height - 5 && input.CurrentMouseState.Y <= ScreenManager.ViewRect.Height))
                cam.Pos += new Vector2(0, 20 * 1 / cam.Zoom);
            //-----------------------------------------------


            // przyciski----------------------------------------
            foreach (Button but in selectionButtonList)
                but.HandleInput(input);

            foreach (Button but in buildButtonList)
                but.HandleInput(input);

            foreach (Button but in controlUnitButtonList)
                but.HandleInput(input);

            foreach (Button but in controlBuildingButtonList)
                but.HandleInput(input);
            //--------------------------------------------------

            // jeśli budujemy i wcisnieto prawy to anuluj budowe
            if (buildingStarted && input.IsNewMRightButtonPressed())
            {
                buildingStarted = false;
                gamePlayScreen.EntityManager.CanSelect = true;
            }

            if (buildingStarted && input.IsNewMLeftButtonPressed())
            {
                if (!mouseFirstPressed && !topBar.Contains(mousePos) && !bottomBar.Contains(mousePos))
                {
                    mouseFirstPressed = true;
                    buildingOrigin = mousePos;
                }
            }

            if (buildingStarted && mouseFirstPressed)
            {
                // uaktualniaj rotacje
                buildingRot = (float) -Math.Atan2(mousePos.X - buildingOrigin.X, mousePos.Y - buildingOrigin.Y);
            }

            if (mouseFirstPressed && input.CurrentMouseState.LeftButton == ButtonState.Released)
            {
                buildingStarted = false;
                mouseFirstPressed = false;
                RTSGame game = (RTSGame)(ScreenManager.Game);
               
                Point pojnt = game.Camera.transformPoint(buildingOrigin, game.GraphicsDevice);
                Vector2 poz = new Vector2(pojnt.X, pojnt.Y);
                gamePlayScreen.EntityManager.Build(buildingType, poz, buildingRot);
                gamePlayScreen.EntityManager.CanSelect = true;
                buildingRot = 0;
                eventHandled = true;
            }
        }

        public override void Exit()
        {
            base.Exit();

            ((RTSGame)ScreenManager.Game).Camera.Reset();
        }

        #endregion

        #region metody private

        #region rysowanie

        private void drawTopBar(ExtendedSpriteBatch exSpriteBatch)
        {
            exSpriteBatch.FillRectangle(topBar, Color.LightGray);


            // rysowanie ilości piniendzy
            int cash = gamePlayScreen.EntityManager.Kasa; // chwilowo
            string cashString = "$" + cash.ToString();

            Vector2 stringSize = ScreenManager.Font.MeasureString(cashString.ToString());
            Vector2 stringPos;
            stringPos.X = topBar.X + 10;
            stringPos.Y = (topBar.Height - stringSize.Y) / 2;
            exSpriteBatch.FillRectangle(new Rectangle((int)stringPos.X, (int)stringPos.Y, 100, (int)stringSize.Y), Color.Gray * 0.7f);

            exSpriteBatch.DrawString(ScreenManager.Font, cashString, stringPos, Color.Black);
            int lastRight = (int)stringPos.X + 100;

            // rysowanie ilosci jednostek
            EntityManager.Stats stats = gamePlayScreen.EntityManager.Stat;

            // team1
            lastRight += 10;
            exSpriteBatch.FillRectangle(new Rectangle(lastRight, (int)stringPos.Y, 195, (int)stringSize.Y), Color.MediumAquamarine);
            exSpriteBatch.DrawString(ScreenManager.Font, "Buildings: " + stats.BuildingsACount.ToString() + "  Units: " + stats.UnitsACount.ToString(), new Vector2(lastRight + 5, stringPos.Y), Color.Black);

            // team2
            lastRight += 200;
            exSpriteBatch.FillRectangle(new Rectangle(lastRight, (int)stringPos.Y, 195, (int)stringSize.Y), Color.OrangeRed);

            exSpriteBatch.DrawString(ScreenManager.Font, "Buildings: " + stats.BuildingsBCount.ToString() + "  Units: " + stats.UnitsBCount.ToString(), new Vector2(lastRight + 5, stringPos.Y), Color.Black);
            lastRight += 195;

            // rysowanie guzika MENU
            int width = 100;
            int remaining = topBar.Right - lastRight;

            buttonRect = new Rectangle(lastRight + remaining/2 - width/2, (int)stringPos.Y, width, (int)stringSize.Y) ;
            //buttonRect = new Rectangle(lastRight + 5, (int)stringPos.Y, topBar.X + topBar.Width - lastRight - 10, (int)stringSize.Y);
            exSpriteBatch.FillRectangle(buttonRect, buttonColor * 0.7f);
            exSpriteBatch.DrawString(ScreenManager.Font, "Menu", new Vector2(buttonRect.Left + buttonRect.Width/2 - ScreenManager.Font.MeasureString("Menu").X/2, stringPos.Y), Color.Black);
        }

        private void drawBottomBar(ExtendedSpriteBatch exSpriteBatch)
        {
            exSpriteBatch.FillRectangle(bottomBar, Color.LightGray);

            drawMiniMap(exSpriteBatch);

            drawSelectionArea(exSpriteBatch);

            drawInfoArea(exSpriteBatch);

            drawBuildArea(exSpriteBatch);

        }

        private void drawMiniMap(ExtendedSpriteBatch exSpriteBatch)
        {
            Map map = gamePlayScreen.Map;
            Camera cam = ((RTSGame)(ScreenManager.Game)).Camera;
            Rectangle viewRect = ScreenManager.ViewRect;

            // rysowanie ramki
            exSpriteBatch.FillRectangle(miniMap, Color.Gray);

            // rysowanie tekstu nad minimapa
            Vector2 textSize = ScreenManager.Font.MeasureString("Minimap");
            Vector2 textPos = new Vector2();
            textPos.X = miniMap.Left + miniMap.Width / 2 - textSize.X / 2;
            textPos.Y = miniMap.Top - textSize.Y - 5;

            exSpriteBatch.DrawString(ScreenManager.Font, "Minimap", textPos, Color.Black);

            //rysowanie minimapy
            float scale = (float)miniMap.Width /(float) map.Bounds.Width;
            foreach (Entity asd in gamePlayScreen.EntityManager.UnitAList)
            {
                int X = (int)((float)(asd.Position.X - map.Bounds.X) * scale) + miniMap.X;
                int Y = (int)((float)(asd.Position.Y - map.Bounds.Y) * scale) + miniMap.Y;

                if(!miniMap.Contains(new Point(X, Y)))
                    continue;

                exSpriteBatch.FillRectangle(new Rectangle(X, Y, 3, 3), Color.Blue, 0f);
            }

            foreach (Entity asd in gamePlayScreen.EntityManager.UnitBList)
            {
                int X = (int)((float)(asd.Position.X - map.Bounds.X) * scale) + miniMap.X;
                int Y = (int)((float)(asd.Position.Y - map.Bounds.Y) * scale) + miniMap.Y;

                if (!miniMap.Contains(new Point(X, Y)))
                    continue;

                exSpriteBatch.FillRectangle(new Rectangle(X, Y, 3, 3), Color.Red, 0f);
            }

            // rysowanie pozycji kamery
            int posX = (int)((float)(cam.Pos.X - map.Bounds.X) * scale) + miniMap.X;
            int posY = (int)((float)(cam.Pos.Y - map.Bounds.Y) * scale) + miniMap.Y;
            int width = (int)(viewRect.Width * scale / cam.Zoom);
            int height = (int)(viewRect.Height * scale / cam.Zoom);

            if (posX < miniMap.X)
            {
                width -= miniMap.X - posX;
                posX = miniMap.X;
            }
            if (posY < miniMap.Y)
            {
                height -= miniMap.Y - posY;
                posY = miniMap.Y;
            }
            if (posX + width > miniMap.Right)
            {
                width -= posX + width - miniMap.Right;
            }
            if (posY + height > miniMap.Bottom)
            {
                height -= posY + height - miniMap.Bottom;
            }

            exSpriteBatch.FillRectangle(new Rectangle(posX, posY, width, height), Color.White * 0.3f, 0f);

        }

        private void drawSelectionArea(ExtendedSpriteBatch exSpriteBatch)
        {
            // rysowanie ramki
            exSpriteBatch.DrawRectangle(selectionArea, Color.Gray);

            // rysowanie tekstu
            Vector2 textSize = ScreenManager.Font.MeasureString("Unit Selection");
            Vector2 textPos = new Vector2();
            textPos.X = selectionArea.Left + selectionArea.Width / 2 - textSize.X / 2;
            textPos.Y = selectionArea.Top - textSize.Y - 5;

            exSpriteBatch.DrawString(ScreenManager.Font, "Unit Selection", textPos, Color.Black);

            // rysowanie jednostek
            List<Unit> selection = gamePlayScreen.EntityManager.Selection;

            int[] typeCountTab = new int[typesCount];

            // liczenie do tablicy ile jest roznych typów
            foreach (Unit unit in selection)
            {
                if (unit.Health <= 0)
                    continue;

                if (unit.GetType() == typeof(Grunt))
                    typeCountTab[0]++;
                else if (unit.GetType() == typeof(Tank))
                    typeCountTab[1]++;
                else if (unit.GetType() == typeof(Helicopter))
                    typeCountTab[2]++;
            }

            // rysowanie
            int ile = 0;
            Vector2 pos = new Vector2();
            pos.Y = selectionArea.Top + 5;

            for(int i = 0; i < typesCount; ++i)
            {
                selectionButtonList[i].IsActive = false;
                selectionButtonList[i].IsHidden = true;

                if (typeCountTab[i] > 0)
                {
                    // tutaj aktywujemy i ustawiamy miejsce guzika
                    pos.X = selectionArea.Left + 5 + ile * (50 + 5);

                    selectionButtonList[i].IsActive = true;
                    selectionButtonList[i].IsHidden = false;
                    selectionButtonList[i].Pos = pos;

                    float testX = pos.X + (typeTexTab[i].Width/2 - ScreenManager.Font.MeasureString(typeCountTab[i].ToString()).X/2)/2;
                    float testY = pos.Y + 45;
                    exSpriteBatch.DrawString(ScreenManager.Font, typeCountTab[i].ToString(), new Vector2(testX, testY), Color.Black);

                    ++ile;
                }
            }
        }

        private void drawInfoArea(ExtendedSpriteBatch exSpriteBatch)
        {
            // rysowanie ramki
            exSpriteBatch.DrawRectangle(infoArea, Color.Gray);

            // rysowanie tekstu
            Vector2 textSize = ScreenManager.Font.MeasureString("Unit info/control");
            Vector2 textPos = new Vector2();
            textPos.X = infoArea.Left + infoArea.Width / 2 - textSize.X / 2;
            textPos.Y = infoArea.Top - textSize.Y - 5;

            exSpriteBatch.DrawString(ScreenManager.Font, "Unit info/control", textPos, Color.Black);

            // rysowanie portretu
            Rectangle portraitArea = new Rectangle(infoArea.X + 5, infoArea.Y + 5, 100, 100);

            //if(lista budynkow jest pusta i lista jednostek pusta)
            //rysuj czarny prostokat jako portret
            //else if(lista budynkow pusta lista jednostek pelna)
            //rysuj portret jednostki, jej hp, schemat obrazen oraz kontrolki do sterowania postawą i szykiem
            //else if(lista budynkow niepusta lista jednostek pusta)
            //rysuj portret i hp budynku oraz kontrolki do budowy kolejki i sama kolejke
            if (gamePlayScreen.EntityManager.Selection.Count > 0)
            {
                int unitID = gamePlayScreen.EntityManager.getUnitID(gamePlayScreen.EntityManager.Selection[0]);
                exSpriteBatch.Draw(typeTexTab[unitID], portraitArea, Color.White);

                // aktywacja guzikow kontroli jednostki
                foreach (Button but in controlUnitButtonList)
                {
                    but.IsActive = true;
                    but.IsHidden = false;
                }

                // rysowanie HP
                Unit unit = gamePlayScreen.EntityManager.Selection[0];

                Rectangle redBar = new Rectangle(portraitArea.Left, portraitArea.Bottom + 5, portraitArea.Width, 8);
                exSpriteBatch.FillRectangle(redBar, Color.Red);

                exSpriteBatch.FillRectangle(new Rectangle(redBar.X, redBar.Y, redBar.Width * unit.Health / unit.MaxHealth, redBar.Height), Color.Chartreuse);

                string str = unit.Health.ToString() + "/" + unit.MaxHealth.ToString();
                Vector2 rozmiar = ScreenManager.Font.MeasureString(str);

                exSpriteBatch.DrawString(ScreenManager.Font, str, new Vector2(redBar.X + redBar.Width / 2 - rozmiar.X / 2, redBar.Bottom), Color.Black);


            }
            else
            {
                exSpriteBatch.FillRectangle(portraitArea, Color.Black * 0.6f);
                foreach (Button but in controlUnitButtonList)
                {
                    but.IsActive = false;
                    but.IsHidden = true;
                }
            }
        }

        private void drawBuildArea(ExtendedSpriteBatch exSpriteBatch)
        {
            // rysowanie ramki
            exSpriteBatch.DrawRectangle(buildArea, Color.Gray);

            // rysowanie tekstu
            Vector2 textSize = ScreenManager.Font.MeasureString("build menu");
            Vector2 textPos = new Vector2();
            textPos.X = buildArea.Left + buildArea.Width / 2 - textSize.X / 2;
            textPos.Y = buildArea.Top - textSize.Y - 5;

            exSpriteBatch.DrawString(ScreenManager.Font, "build menu", textPos, Color.Black);
        }

        #endregion

        #region obsluga guzikow

        private void handleControlButtons()
        {
            foreach (Button but in controlUnitButtonList)
            {
                if (but.IsPressed)
                {
                    switch (but.ID)
                    {
                        case 0:
                            gamePlayScreen.EntityManager.SetSelectedUnitStance(Unit.Moodes.Defensive);
                            break;
                        case 1:
                            gamePlayScreen.EntityManager.SetSelectedUnitStance(Unit.Moodes.Aggressive);
                            break;
                        case 2:
                            gamePlayScreen.EntityManager.SetFormation(0);
                            break;
                        case 3:
                            gamePlayScreen.EntityManager.SetFormation(1);
                            break;
                        case 4:
                            gamePlayScreen.EntityManager.SetFormation(2);
                            break;
                    }
                }
            }
        }   

        private void handleSelectionButtons()
        {
            foreach (Button but in selectionButtonList)
            {
                if (but.IsPressed)
                {
                    Type type = typeof(Grunt);
                    List<Unit> chosen = gamePlayScreen.EntityManager.Selection;
                    List<Unit> temp = new List<Unit>();

                    switch(but.ID)
                    {
                        case 0:
                            type = typeof(Grunt);
                            break;
                        case 1:
                            type = typeof(Tank);
                            break;
                        case 2:
                            type = typeof(Helicopter);
                            break;
                    }

                    foreach (Unit unit in chosen)
                    {
                        if (unit.GetType() == type)
                        {
                            temp.Add(unit);

                            unit.select(true);
                        }
                        else
                            unit.select(false);
                    }

                    gamePlayScreen.EntityManager.Selection = temp;
                    but.IsActive = false;
                    but.IsHidden = true;
                }
            }
        }

        private void handleBuildButtons()
        {
            foreach (Button but in buildButtonList)
            {
                if (but.IsPressed)
                {
                    buildingStarted = true;
                    buildingType = but.ID;
                    gamePlayScreen.EntityManager.CanSelect = false;
                }
            }
        }

        #endregion

        #endregion
    }
}
